from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from common.setting import settings
from middleware.middleware import register_middleware
from middleware.cors import register_cors
from router import register_router
from common.db_init import init_table, init_data
from common.connectionmanager import ConnectionManager
from common.custom_log import my_logger

app = FastAPI(title=settings.app_name, description=settings.description, version=settings.version,
              openapi_url=settings.openapi_url)

# 设置静态文件目录 访问路径http://127.0.0.1:8000/static/hot_heart.png
app.mount(f'/{settings.staticPath}', StaticFiles(directory=settings.staticPath), name=settings.staticPath)

# 设置跨域
register_cors(app)

# # 注册路由
register_router(app)

register_middleware(app)

# 新建表 is_drop 是否删除表
# init_table(True)

# 设置默认数据
# init_data()


@app.on_event("shutdown")
async def shutdown_event():
    my_logger.error("项目已关闭!!！")


@app.on_event("startup")
async def startup_event():
    manager = ConnectionManager()
    # 设置发布者属性对象
    app.state.manager = manager
    my_logger.info("项目启动!!！")
